package com.welkom.everydate.security.implementations;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.Assert;

import com.welkom.everydate.dao.RoleDao;
import com.welkom.everydate.domain.Authority;
import com.welkom.everydate.domain.Role;

/**
 * @author welkom Zhang
 *
 */
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	
	private Map<String, String> map;
	
	@Resource
	RoleDao roleDao;
	private boolean isFirst = true;
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		if(this.map==null){
			map=new HashMap<String,String>();
			List<Role> roles=roleDao.getAllRoles();
			for(Role role:roles){
				map.put(role.getRoleName(), role.getDefaultRoleUrl());
			}
		}
		String url = "";
		Collection<GrantedAuthority> authCollection = (Collection<GrantedAuthority>) authentication.getAuthorities();

		if (authCollection.isEmpty()) {
			return;
		}
	
		if (isFirst) {
			GrantedAuthority[] a = new Role[]{};
			url = map.get(authCollection.toArray(a)[0].getAuthority());
			response.sendRedirect(request.getContextPath() + url);
			return;
		}
	
		for (GrantedAuthority auth : authCollection) {
			url = map.get(auth.getAuthority());
		}
		response.sendRedirect(url);
	}
	/**
	 */
	public void setMultipleAuth(boolean isFirst) {
		this.isFirst = isFirst;
	}
}
